#include "myplaylistmodel.h"
#include "config.h"
#include <QSqlQuery>
#include <QSqlResult>
#include "log/EZQLOG.h"


MyPlayListModel::MyPlayListModel()
{
    _dbid = 0;
}

MyPlayListModel::~MyPlayListModel()
{

}

int MyPlayListModel::dbid() const
{
    return _dbid;
}

void MyPlayListModel::setDbid(int dbid)
{
    _dbid = dbid;
}
void MyPlayListModel::addSong(SongModel *song,bool updateDb)
{
    NormalPlayListModel::addSong(song);
    if(updateDb){ //因为我懒,不写单条更新,所在调用 saveSongsToDB 全部更新
        saveSongsToDB();
    }
}

void MyPlayListModel::removeSong(SongModel *song,bool updateDb)
{
    NormalPlayListModel::removeSong(song);
    if(updateDb){ //因为我懒,不写单条更新,所在调用 saveSongsToDB 全部更新
        saveSongsToDB();
    }
}

EZTally::EZTallyAutoPtr MyPlayListModel::shareMyPlayList(bool refresh)
{
    checkDBState();

    static QMutex mutex;
    QMutexLocker locker(&mutex);

    static EZTally::EZTallyArray<MyPlayListModel*> *arr = new EZTally::EZTallyArray<MyPlayListModel*>();

    if(refresh || arr->Count()==0){
        QString sql("select * from ");
        sql.append(MyPlayListModel_DB_TABLE);

        QSqlDatabase db = Config::defaultConfig()->dataBase();
        QSqlQuery query(db);
        query.exec(sql);

        EZTally::EZTallyArray<MyPlayListModel*> *newArr = new EZTally::EZTallyArray<MyPlayListModel*>(*arr);
        arr->Clear();
        while(query.next()){

            int dbid = query.value(0).toInt();
            MyPlayListModel *mpm = 0;
            for(int i=0;i<newArr->Count();i++){
                MyPlayListModel *p = newArr->ObjectAtIndex(i);
                if(dbid == p->dbid()){ //same
                    mpm = p;
                    break;
                }
            }
            if(mpm==0){
                mpm = new MyPlayListModel();
            }

            mpm->setDbid(dbid);
            mpm->setName(query.value(1).toString());

            arr->AddObject(mpm);
            mpm->Release();
        }
        newArr->Release();
    }

    EZTally::EZTallyArray<MyPlayListModel*> *nowArr = new EZTally::EZTallyArray<MyPlayListModel*>(*arr);
    EZTally::EZTallyAutoPtr ptr;
    ptr.Set(nowArr);
    nowArr->Release();
    return ptr;

}

EZTally::EZTallyAutoPtr MyPlayListModel::playListFromDB()
{
    checkDBState();

    QString sql("select * from ");
    sql.append(MyPlayListModel_DB_TABLE);

    QSqlDatabase db = Config::defaultConfig()->dataBase();
    QSqlQuery query(db);
    query.exec(sql);
    EZTally::EZTallyArray<MyPlayListModel*> *arr = new EZTally::EZTallyArray<MyPlayListModel*>();
    while(query.next()){

        MyPlayListModel *mpm = new MyPlayListModel();
        mpm->setDbid(query.value(0).toInt());
        mpm->setName(query.value(1).toString());

        arr->AddObject(mpm);
        mpm->Release();
    }
    query.finish();

    EZTally::EZTallyAutoPtr ptr;
    ptr.Set(arr);
    arr->Release();
    return ptr;
}

void MyPlayListModel::saveToDB()
{
    QSqlDatabase db = Config::defaultConfig()->dataBase();
    QString sql("insert or replace into %1 values(:id,:name);");
    sql = sql.arg(MyPlayListModel_DB_TABLE);
    QSqlQuery query(db);
    query.prepare(sql);
    if(_dbid>0){
        query.bindValue(":id",_dbid);
    }
    query.bindValue(":name",_name);
    bool isSave = query.exec();
    if(isSave && _dbid<=0){
        QString nidSql("select last_insert_rowid() id");
//        nidSql.arg(MyPlayListModel_DB_TABLE);
        QSqlQuery idquery(db);
        idquery.exec(nidSql);
        if(idquery.next()){
            _dbid = idquery.value(0).toInt();
        }
    }
    EZDebug << "save is : " << isSave;
}
bool MyPlayListModel::removeOnDB()
{

    bool code = false;

    {
        QSqlDatabase db = Config::defaultConfig()->dataBase();
        QString sql("delete from %1 where playListdbid = %2;");
        sql = sql.arg(MyPlayListModel_Songs_DB_TABLE).arg(_dbid);
        QSqlQuery query(db);
        code = query.exec(sql);
    }
    if(code==true){
        QSqlDatabase db = Config::defaultConfig()->dataBase();
        QString sql("delete from %1 where id = %2;");
        sql = sql.arg(MyPlayListModel_DB_TABLE).arg(_dbid);
        QSqlQuery query(db);
        code = query.exec(sql);
    }

    return code;
}

void MyPlayListModel::fillSongsFromDB()
{

    this->songs->Clear();

    QString sql("select * from %1 where  id in(select  songdbid from %2 where playListdbid=%3)");
    sql = sql.arg(SongModel_DB_TABLE).arg(MyPlayListModel_Songs_DB_TABLE).arg(_dbid);

    QSqlDatabase db = Config::defaultConfig()->dataBase();
    QSqlQuery query(db);
    query.exec(sql);

    while(query.next()){
        SongModel *song = new SongModel();
        song->initSongWith(query);
        addSong(song);
    }
    query.finish();
}
void MyPlayListModel::saveSongsToDB()
{
    if(_dbid<=0){
        return ;
    }
    QSqlDatabase db = Config::defaultConfig()->dataBase();
    db.transaction();

    QSqlQuery query(db);
    //clear old
    QString clearSql("delete from %1 where playListdbid = %2");
    clearSql = clearSql.arg(MyPlayListModel_Songs_DB_TABLE).arg(_dbid);
    bool isClear =  query.exec(clearSql);

    QString sql("insert into %1 values (:playListdbid,:songdbid)");
    sql = sql.arg(MyPlayListModel_Songs_DB_TABLE);

    for(int i=0;i<count();i++){
        SongModel *song = songAtIndex(i);
        song->saveToDB(false);
        query.prepare(sql);
        query.bindValue(":playListdbid",_dbid);
        query.bindValue(":songdbid",song->dbid());
        bool isSave = query.exec();
        if(isSave==false){
            EZDebug << "add song to myplaylist error";
        }
        query.finish();
    }
    db.commit();
}

void MyPlayListModel::checkDBState()
{
    static int isCheck = false;
    if(isCheck == true){
        return;
    }

    SongModel::checkDBState();

    { // create database
        QString sql(QString("create table ")+MyPlayListModel_DB_TABLE+"("
                    "id integer primary key autoincrement,"
                    "name TEXT"
                    ")");

        QSqlDatabase db = Config::defaultConfig()->dataBase();
        QSqlQuery query(db);
        bool isCreate = query.exec(sql);
        EZDebug << "init " << MyPlayListModel_DB_TABLE << isCreate;
    }

    {
        QString sql(QString("create table ")+MyPlayListModel_Songs_DB_TABLE+"("
                    "playListdbid integer,"
                    "songdbid integer,"
                    "primary key (playListdbid,songdbid)"
                    ")");

        QSqlDatabase db = Config::defaultConfig()->dataBase();
        QSqlQuery query(db);
        bool isCreate = query.exec(sql);
        EZDebug << "init " << MyPlayListModel_Songs_DB_TABLE << isCreate;
    }



    isCheck = true;
}
